<?php
defined( '_JEXEC' ) or die( 'Acesso restrito ao Joomla!' );
jimport( 'joomla.application.component.controller' );
class AloController extends JController
{
	function __construct( $default = array() )
	{
		parent::__construct( $default );
		$this->registerTask( 'add', 'edit' );
		$this->registerTask( 'apply', 'save' );
		$this->registerTask( 'unpublish', 'publish' );
	}
	function edit()
	{
		global $option;
		$row =& JTable::getInstance('alo', 'Table');
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		$id = $cid[0];
		$row->load($id);
		HTML_alo::editaNome($row, $option);
	}
	function save()
	{
		global $option;
		JRequest::checkToken() or die( 'Token Invlido' );
		$row =& JTable::getInstance('alo', 'Table');
		if (!$row->bind(JRequest::get('post'))) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1);</script>\n";
			exit();
		}

		$row->nome = JRequest::getVar( 'nome', '', 'post','string', JREQUEST_ALLOWRAW );
		$row->id = (int) $row->id;
		if (!$row->store()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1);</script>\n";
			exit();
		}
		switch ($this->_task)
		{
			case 'apply':
				$msg = 'Alterações efetuadas com sucesso';
				$link = 'index.php?option=' . $option . '&task=edit&cid[]='. $row->id;
				break;
			case 'save':
			default:
				$msg = 'O Nome foi salvo com sucesso';
				$link = 'index.php?option=' . $option;
				break;
		}

		$this->setRedirect($link, $msg);
	}

	function mostraNomes()
	{
		global $option, $mainframe;
		$limit = JRequest::getVar('limit', $mainframe->getCfg('list_limit'));
		$limitstart = JRequest::getVar('limitstart', 0);
		$db =& JFactory::getDBO();
		// Obtem a quantidade de registros
		$query = "SELECT count(*) FROM #__alo";
		$db->setQuery( $query );
		$total = $db->loadResult();
		$query = "SELECT * FROM #__alo";
		$db->setQuery( $query, $limitstart, $limit );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		jimport('joomla.html.pagination');
		$pageNav = new JPagination($total, $limitstart, $limit);
		HTML_alo::mostraNomes( $option, $rows, $pageNav );
	}

	function remove()
	{
		global $option;
		$cid = JRequest::getVar( 'cid', array(), '', 'array' );
		$db =& JFactory::getDBO();
		if(count($cid))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = "DELETE FROM #__alo WHERE id IN ( $cids )";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window.	history.go(-1); </script>\n";
			}
		}
		$this->setRedirect( 'index.php?option=' . $option );
	}

	function publish()
	{
		global $option;
		$cid = JRequest::getVar( 'cid', array(), '', 'array' );
		if( $this->_task == 'publish')
		{
			$publish = 1;
		}
		else
		{
			$publish = 0;
		}
		$aloTable =& JTable::getInstance('alo', 'Table');
		$aloTable->publish($cid, $publish);
		$this->setRedirect( 'index.php?option=' . $option );
	}
}
?>